import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:intl/intl.dart';
import '../models/habit.dart';
import '../services/habit_provider.dart';
import '../utils/app_theme.dart';
import 'edit_habit_screen.dart';

class HabitDetailScreen extends StatelessWidget {
  final Habit habit;
  
  const HabitDetailScreen({
    super.key,
    required this.habit,
  });
  
  Widget _buildIconForHabit(String iconName) {
    switch (iconName) {
      case 'water':
        return const Icon(Icons.water_drop, size: 32);
      case 'exercise':
        return const Icon(Icons.fitness_center, size: 32);
      case 'book':
        return const Icon(Icons.book, size: 32);
      case 'meditation':
        return const Icon(Icons.self_improvement, size: 32);
      case 'notes':
        return const Icon(Icons.note, size: 32);
      case 'sleep':
        return const Icon(Icons.nightlight, size: 32);
      case 'study':
        return const Icon(Icons.school, size: 32);
      default:
        return const Icon(Icons.list, size: 32);
    }
  }
  
  void _deleteHabit(BuildContext context) {
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('确认删除'),
        content: const Text('确定要删除这个习惯吗？删除后无法恢复。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Provider.of<HabitProvider>(context, listen: false)
                .deleteHabit(habit.id);
              Navigator.of(context).pop();
              Navigator.of(context).pop();
            },
            child: const Text('删除', style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    );
  }
  
  void _editHabit(BuildContext context) {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => EditHabitScreen(habit: habit),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final habitProvider = Provider.of<HabitProvider>(context);
    final completedDates = habit.completedDates;
    final streak = habit.getStreakCount();
    final isCompletedToday = habit.isCompletedToday();
    
    return Scaffold(
      appBar: AppBar(
        title: const Text('习惯详情'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.of(context).pop(),
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.edit),
            onPressed: () => _editHabit(context),
          ),
          IconButton(
            icon: const Icon(Icons.delete_outline),
            onPressed: () => _deleteHabit(context),
          ),
        ],
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Habit header
            Container(
              padding: const EdgeInsets.all(16),
              decoration: AppTheme.cardDecoration,
              child: Row(
                children: [
                  Container(
                    padding: const EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      color: Color(habit.colorValue).withOpacity(0.1),
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: _buildIconForHabit(habit.icon),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          habit.name,
                          style: AppTheme.headingStyle.copyWith(fontSize: 20),
                        ),
                        const SizedBox(height: 4),
                        Text(
                          '${habit.frequency} · ${habit.amount}',
                          style: AppTheme.smallTextStyle,
                        ),
                        if (habit.description.isNotEmpty) ...[
                          const SizedBox(height: 8),
                          Text(
                            habit.description,
                            style: AppTheme.bodyStyle,
                          ),
                        ],
                      ],
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 20),
            
            // Today's status
            Container(
              padding: const EdgeInsets.all(16),
              decoration: AppTheme.cardDecoration,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '今日状态: ${isCompletedToday ? '已完成' : '未完成'}',
                    style: AppTheme.subheadingStyle,
                  ),
                  const SizedBox(height: 16),
                  ElevatedButton.icon(
                    onPressed: () {
                      habitProvider.toggleHabitCompletion(habit);
                    },
                    icon: Icon(isCompletedToday ? Icons.remove : Icons.check),
                    label: Text(isCompletedToday ? '取消标记为完成' : '标记为已完成'),
                    style: isCompletedToday
                        ? OutlinedButton.styleFrom(
                            foregroundColor: AppTheme.errorColor,
                          )
                        : AppTheme.primaryButtonStyle,
                  ),
                ],
              ),
            ),
            const SizedBox(height: 20),
            
            // Streak info
            Container(
              padding: const EdgeInsets.all(16),
              decoration: AppTheme.cardDecoration,
              child: Row(
                children: [
                  Expanded(
                    child: Column(
                      children: [
                        const Icon(
                          Icons.local_fire_department,
                          size: 40,
                          color: Colors.orange,
                        ),
                        const SizedBox(height: 8),
                        Text(
                          '$streak',
                          style: AppTheme.headingStyle,
                        ),
                        const Text('当前连续'),
                      ],
                    ),
                  ),
                  Expanded(
                    child: Column(
                      children: [
                        const Icon(
                          Icons.calendar_month,
                          size: 40,
                          color: AppTheme.primaryColor,
                        ),
                        const SizedBox(height: 8),
                        Text(
                          '${completedDates.length}',
                          style: AppTheme.headingStyle,
                        ),
                        const Text('总完成次数'),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 20),
            
            // Completion history
            Container(
              padding: const EdgeInsets.all(16),
              decoration: AppTheme.cardDecoration,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text('完成历史', style: AppTheme.subheadingStyle),
                  const SizedBox(height: 16),
                  if (completedDates.isEmpty)
                    const Text(
                      '尚未有完成记录',
                      style: TextStyle(color: AppTheme.textSecondaryColor),
                    )
                  else
                    // Calendar squares (simplified version)
                    Wrap(
                      spacing: 8,
                      runSpacing: 8,
                      children: List.generate(
                        30, // Show last 30 days
                        (index) {
                          final date = DateTime.now().subtract(Duration(days: 29 - index));
                          final isCompleted = completedDates.any((d) =>
                            d.year == date.year &&
                            d.month == date.month &&
                            d.day == date.day);
                          
                          return Tooltip(
                            message: DateFormat('yyyy-MM-dd').format(date),
                            child: Container(
                              width: 24,
                              height: 24,
                              decoration: BoxDecoration(
                                color: isCompleted ? AppTheme.successColor : Colors.transparent,
                                border: Border.all(
                                  color: isCompleted
                                      ? AppTheme.successColor
                                      : AppTheme.borderColor,
                                ),
                                borderRadius: BorderRadius.circular(4),
                              ),
                              child: isCompleted
                                  ? const Icon(Icons.check, size: 16, color: Colors.white)
                                  : null,
                            ),
                          );
                        },
                      ),
                    ),
                ],
              ),
            ),
            const SizedBox(height: 20),
            
            // Reminders
            Container(
              padding: const EdgeInsets.all(16),
              decoration: AppTheme.cardDecoration,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text('提醒时间', style: AppTheme.subheadingStyle),
                  const SizedBox(height: 16),
                  if (habit.reminderTimes.isEmpty)
                    const Text(
                      '未设置提醒',
                      style: TextStyle(color: AppTheme.textSecondaryColor),
                    )
                  else
                    ...habit.reminderTimes.map((time) => ListTile(
                      leading: const Icon(Icons.alarm),
                      title: Text(time),
                      dense: true,
                      contentPadding: EdgeInsets.zero,
                    )),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
